pictureURL="http://221.0.77.189:50/gis_static_resource/images/";
gisstaticresourcebaseurl = "http://221.0.77.189:50/gis_static_resource";
gisUrl = "http://221.0.77.189:6080";


/**
 * 加载底图
 * @param map
 */
function loadBaseMap(map) {
    require([
        'esri/layers/WebTiledLayer',
        'dojo/domReady!'
    ], function (WebTiledLayer) {
        var baseLayer = new WebTiledLayer('http://${subDomain}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL=${col}&TILEROW=${row}&TILEMATRIX=${level}&tk=79fa0ad8cf51823310e763e1fb3bdb22', {
            subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"]
        })
        var annotationLayer = new WebTiledLayer('http://${subDomain}.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL=${col}&TILEROW=${row}&TILEMATRIX=${level}&tk=79fa0ad8cf51823310e763e1fb3bdb22', {
            subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"]
        })

        map.addLayers([baseLayer, annotationLayer]);
    })
}

function loadBaseMapResource(callback) {

    require([
        'esri/layers/WebTiledLayer',
        'dojo/domReady!'
    ], function (WebTiledLayer) {
        var baseLayer = new WebTiledLayer('http://${subDomain}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL=${col}&TILEROW=${row}&TILEMATRIX=${level}&tk=79fa0ad8cf51823310e763e1fb3bdb22', {
            subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"]
        })
        var annotationLayer = new WebTiledLayer('http://${subDomain}.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL=${col}&TILEROW=${row}&TILEMATRIX=${level}&tk=79fa0ad8cf51823310e763e1fb3bdb22', {
            subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"]
        })
        var imgbaseLayer = new WebTiledLayer('http://${subDomain}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL=${col}&TILEROW=${row}&TILEMATRIX=${level}&tk=79fa0ad8cf51823310e763e1fb3bdb22', {
            subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"]
        });
        var imgannotationLayer = new WebTiledLayer('http://${subDomain}.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL=${col}&TILEROW=${row}&TILEMATRIX=${level}&tk=79fa0ad8cf51823310e763e1fb3bdb22', {
            subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"]
        });

        callback([baseLayer, annotationLayer, imgbaseLayer, imgannotationLayer]);
    })

}

function loadVecMap(map, arr) {
    map.removeLayer(arr[2]);
    map.removeLayer(arr[3]);
    map.addLayer(arr[0], 0);
    map.addLayer(arr[1], 1);
}

function loadImgMap(map, arr) {
    map.removeLayer(arr[0]);
    map.removeLayer(arr[1]);
    map.addLayer(arr[2], 0);
    map.addLayer(arr[3], 1);
}

/**
 * 加载图层
 * @param map
 * @param callback
 */
function loadLayers(map, callback) {
    require([
        "esri/layers/FeatureLayer",
        "esri/InfoTemplate",
        "esri/symbols/SimpleMarkerSymbol",
        "esri/symbols/PictureMarkerSymbol",
        "esri/symbols/SimpleLineSymbol",
        "esri/symbols/SimpleFillSymbol",
        "esri/Color",
        "esri/renderers/SimpleRenderer",
        "dojo/domReady!"
    ], function (FeatureLayer, InfoTemplate, SimpleMarkerSymbol, PictureMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, Color, SimpleRenderer) {

        var smLayer = new FeatureLayer(gisUrl + "/arcgis/rest/services/zyloads_lc/MapServer/0", {
            mode: FeatureLayer.MODE_ONDEMAND,
            outFields: ["ID"],
            infoTemplate: null
        });
        var smSymbol = new PictureMarkerSymbol(gisstaticresourcebaseurl + "/images/ctlp.png", 24, 24);
        smLayer.setRenderer(new SimpleRenderer(smSymbol));
        var hsdLayer = new FeatureLayer(gisUrl + "/arcgis/rest/services/zyloads_lc/MapServer/1", {
            mode: FeatureLayer.MODE_ONDEMAND,
            outFields: ["ID"],
            infoTemplate: null
        });
        var hsdSymbol = new PictureMarkerSymbol(gisstaticresourcebaseurl + "/images/hsd.png", 24, 24);
        hsdLayer.setRenderer(new SimpleRenderer(hsdSymbol));

        var ctlpLayer = new FeatureLayer(gisUrl + "/arcgis/rest/services/zyloads_lc/MapServer/2", {
            mode: FeatureLayer.MODE_ONDEMAND,
            outFields: ["ID"],
            infoTemplate: null
        });
        var ctlpSymbol = new PictureMarkerSymbol(gisstaticresourcebaseurl + "/images/ccctlps.png", 24, 24);
        ctlpLayer.setRenderer(new SimpleRenderer(ctlpSymbol));

        var roads = new FeatureLayer(gisUrl + "/arcgis/rest/services/zyloads/MapServer/1", {
            mode: FeatureLayer.MODE_ONDEMAND,
            outFields: ["*"],
            infoTemplate: null
            // infoTemplate:new InfoTemplate("${LXMC}-${LDXLH}-${UPORDOWN}")
        });

        var centerLine = new FeatureLayer(gisUrl + "/arcgis/rest/services/zyloads/MapServer/0", {
            mode: FeatureLayer.MODE_ONDEMAND,
            outFields: ["*"],
            infoTemplate: null
        })
        map.addLayers([roads, centerLine, hsdLayer, smLayer]);
        hsdLayer.hide();
        ctlpLayer.hide();
        smLayer.hide();

        var selectionFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_DIAMOND, new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT, new Color([255, 0, 0]), 12), new Color([255, 255, 0, 0.25]));
        var selecthsdsymbol = new PictureMarkerSymbol(gisstaticresourcebaseurl + "/images/hsd_select.png", 30, 30);
        var selectctlpsymbol = new PictureMarkerSymbol(gisstaticresourcebaseurl + "/images/ccctlp.png", 30, 30);
        var selectsmsymbol = new PictureMarkerSymbol(gisstaticresourcebaseurl + "/images/ctlp_select.png", 30, 30);

        hsdLayer.setSelectionSymbol(selecthsdsymbol);
        ctlpLayer.setSelectionSymbol(selectctlpsymbol);
        smLayer.setSelectionSymbol(selectsmsymbol);
        roads.setSelectionSymbol(selectionFillSymbol);

        callback({
            110: hsdLayer,
            30: ctlpLayer,
            440: smLayer,
            // 99: centerLine,
            100: roads
        }, {
            110: selecthsdsymbol,
            30: selectctlpsymbol,
            440: selectsmsymbol,
            100: selectionFillSymbol

        })
    });
}

/**
 * 图层显隐
 * @param str
 */
function selectLayers(layers, str) {
    var arr = str.split(",")
    Object.keys(layers).forEach(function (key) {
        if (isInArray(arr, key)) {
            layers[key].show();
        } else {
            if (layers[key]) {
                layers[key].hide();
            }
        }
    });
}

/**
 * 地图框选
 * @param layers
 * @param arr
 * @param callback
 */
function frameSelection(layers, arr, callback) {
    require([
        "custom/util"
    ], function (Util) {
        map.graphics.clear();
        map.infoWindow.hide();
        Object.keys(layers).forEach(function (key) {
            layers[key].clearSelection();
        });
        Util.frameSelection(layers, arr, function (result) {
            setTimeout(function () {
                callback(result)
            }, 1000)
        })
    })
}

/**
 * 判断一个元素是否在数组中
 * @param arr
 * @param value
 * @returns {boolean}
 */
function isInArray(arr, value) {
    for (var i = 0; i < arr.length; i++) {
        if (value === arr[i]) {
            return true;
        }
    }
    return false;
}

/**
 * 查看历史轨迹
 * @param map
 * @param pointArr
 * @param speed
 */
function historicalTrack(map, pointArr, speed, busType) {
    var carGraphic;
    var url;
    require([
        "esri/symbols/SimpleLineSymbol",
        "esri/symbols/SimpleMarkerSymbol",
        "esri/symbols/PictureMarkerSymbol",
        "esri/symbols/SimpleFillSymbol",
        "esri/Color",
        "esri/geometry/Point",
        "esri/geometry/Polyline",
        "esri/layers/GraphicsLayer",
        "esri/graphic",
        "esri/geometry/webMercatorUtils",
        "dojo/_base/array"
    ], function (SimpleLineSymbol, SimpleMarkerSymbol, PictureMarkerSymbol,
                 SimpleFillSymbol, Color, Point, Polyline, GraphicsLayer, Graphic, webMercatorUtils, array
    ) {
        clear();
        points.length = 0;
        var paths = [];
        var path = [];
        array.map(pointArr, function (po) {
            var p = new Point(po.x, po.y);
            var geo = webMercatorUtils.geographicToWebMercator(p);
            points.push(geo);
            path.push([geo.x, geo.y]);
        });
        paths.push(path);

        map.centerAndZoom(points[0], 12);

        // if(!lineSymbol || !carSymbol || !lineLayer || !carLayer) {
        //     lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color("red"), 3);
        //     carSymbol = new PictureMarkerSymbol(gisstaticresourcebaseurl + "/images/locbus.png", 24, 24)
        //     lineLayer = new GraphicsLayer({ id: "lineLayer" });
        //     carLayer = new GraphicsLayer({id: "carLayer"});
        //     map.addLayers([lineLayer,carLayer]);
        // }
        lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color("red"), 3);
        if (busType == 1) {
            url = gisstaticresourcebaseurl + "/images/lzxuncha.png";
        } else if (busType == 2) {
            url = gisstaticresourcebaseurl + "/images/yhxuncha.png";
        } else if (busType == 3) {
            url = gisstaticresourcebaseurl + "/images/yhgsxuncha.png";
        }
        carSymbol = new PictureMarkerSymbol(url, 24, 24);
        lineLayer = new GraphicsLayer({id: "lineLayer"});
        carLayer = new GraphicsLayer({id: "carLayer"});
        map.addLayers([lineLayer, carLayer]);
        var j = 0;
        //开始执行
        if (timer != null) {
            clearInterval(timer);
        }
        carLayer.clear();
        lineLayer.clear();


        var line = new Polyline({"paths": paths, "spatialReference": {"wkid": 3857}});
        var lineGriphic = new Graphic(line, lineSymbol);
        map.getLayer("lineLayer").add(lineGriphic);
        var replayIndex = 0;
        timer = setInterval(function () {
            if (replayIndex == points.length - 1) {
                clearInterval(timer);
            } else {
                // if (replayIndex == 0) {
                //     map.getLayer("lineLayer").clear();
                // }
                var p1 = points[replayIndex];
                var p2 = points[++replayIndex];
                var tempPoints = interpolation(p1, p2, speed);

                var angle = Math.ceil(Angle(p1.x, p1.y, p2.x, p2.y))
                carSymbol.setAngle(angle)   //设置小车角度
                play(tempPoints);
            }
        }, speed * 1000);

        /**
         * 根据回放速度在两点之间进行插值
         */
        function interpolation(pointA, pointB, speed) {
            var tmp = [];
            if (speed == undefined) {
                speed = 1;
            }
            speed = speed - 0.5; //不能大于播放速度
            var count = Math.abs(speed) * 25;
            var disX = (pointB.x - pointA.x) / count;
            var disY = (pointB.y - pointA.y) / count;
            var i = 0;
            while (i <= count) {
                var x = pointA.x + i * disX;
                var y = pointA.y + i * disY;
                tmp.push(new Point({"x": x, "y": y, "spatialReference": {"wkid": 3857}}));
                i++;
            }
            tmp.push(pointB);//防止插值出来的最后一个点到不了B点
            return tmp;
        }

        function play(tmpPoints) {
            var ref = setTimeout(function () {
                if (j < tmpPoints.length - 1) {
                    // var line = new Polyline({ "paths": [[[tmpPoints[j].x, tmpPoints[j].y], [tmpPoints[j + 1].x, tmpPoints[j + 1].y]]], "spatialReference":{"wkid":3857}});
                    // var lineGriphic = new Graphic(line, lineSymbol);
                    // map.getLayer("lineLayer").add(lineGriphic);
                    map.getLayer("carLayer").clear();
                    carGraphic = new Graphic(tmpPoints[j + 1], carSymbol);
                    map.getLayer("carLayer").add(carGraphic);
                    j++;
                    play(tmpPoints);
                } else {
                    j = 0;
                }
            }, 40);  //小车40毫秒换个位置闪现一次，25*40*speed就是两点之间的时间间隔
        }

        function Angle(startx, starty, endx, endy) {
            var tan = 0
            if (endx == startx) {
                tan = Math.atan(0) * 180 / Math.PI
            } else {
                tan = Math.atan(Math.abs((endy - starty) / (endx - startx))) * 180 / Math.PI
            }

            if (endx >= startx && endy >= starty)//第一象限
            {
                return -tan;
            } else if (endx > startx && endy < starty)//第四象限
            {
                return tan;
            } else if (endx < startx && endy > starty)//第二象限
            {
                return tan - 180;
            } else {
                return 180 - tan;  //第三象限
            }
        }

    })
}

/**
 * 车辆定位
 * @param map
 */
function locateACar(map) {
    var url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1547284609840&di=c78d6b4ab23e2c2842a9678032a5d3cb&imgtype=0&src=http%3A%2F%2Fpic39.photophoto.cn%2F20160607%2F0018090919909250_b.jpg";
    require([
        "esri/symbols/SimpleLineSymbol",
        "esri/symbols/SimpleMarkerSymbol",
        "esri/symbols/PictureMarkerSymbol",
        "esri/symbols/SimpleFillSymbol",
        "esri/Color",
        "esri/geometry/Point",
        "esri/geometry/Polyline",
        "esri/graphic",
    ], function (SimpleLineSymbol, SimpleMarkerSymbol, PictureMarkerSymbol, SimpleFillSymbol, Color, Point, Polyline, Graphic) {
        map.graphics.clear();
        map.infoWindow.hide();
        var geometry = new Point({"x": 13412293.350871403, "y": 4475985.482341997, "spatialReference": {"wkid": 3857}})
        var symbol = new PictureMarkerSymbol(url, 24, 24);
        symbol.setAngle(80)
        var graphic = new Graphic(geometry, symbol);
        map.graphics.add(graphic);
        map.infoWindow.setTitle("车辆");
        map.infoWindow.setContent("车牌号：鲁YJP001");
        map.infoWindow.show(geometry);
        map.centerAt(geometry);
    })
}

/**
 * 定位到指定事件
 * @param map
 */
function freeze(map) {
    require(
        [
            "esri/geometry/Point",
            "esri/layers/FeatureLayer",
            "esri/Color",
            "esri/renderers/SimpleRenderer",
            "esri/symbols/PictureMarkerSymbol",
            "esri/tasks/FindParameters",
            "esri/tasks/FindTask",
            "dojo/_base/array",
            "esri/graphic",
            "dojo/domReady!"
        ], function (Point, FeatureLayer, Color, SimpleRenderer, PictureMarkerSymbol, FindParameters, FindTask, array, Graphic) {
            // var line = new FeatureLayer("http://172.19.66.57:6080/arcgis/rest/services/zylc/FeatureServer/3");
            //             // map.addLayer(line)
            //             //
            //             // var findTask = new FindTask("http://172.19.66.57:6080/arcgis/rest/services/showevents/MapServer");
            //             // var findParams = new FindParameters();
            //             // findParams.layerIds = [0];
            //             // findParams.searchFields = ["ID"];
            //             // findParams.searchText = 2;
            //             // findParams.returnGeometry = true;
            //             // findParams.outSpatialReference = map.spatialReference;
            //             // findTask.execute(findParams,showResults);
            //             //
            //             // function showResults(results){
            //             //     map.graphics.clear();
            //             //     var symbol = new PictureMarkerSymbol("http://gif.dabaoku.com/biaoshi/032/006f.gif", 30,30);
            //             //     var items = array.map(results,function (result) {
            //             //         var graphic = result.feature;
            //             //         console.log(graphic)
            //             //         graphic.setSymbol(symbol);
            //             //         map.graphics.add(graphic);
            //             //         map.centerAt(graphic.geometry);
            //             //         return  result.feature.attributes;
            //             //     });
            //             // }

            map.graphics.clear();
            var sms = new PictureMarkerSymbol(gisstaticresourcebaseurl + "/images/dog.jpg", 30, 30);
            var point = new Point({
                "x": 13411978.048129726,
                "y": 4475354.876858645,
                "spatialReference": {"wkid": 3857}
            });
            var event = new Graphic(point, sms);
            map.graphics.add(event);
            map.infoWindow.setTitle("事件" + 101);
            map.infoWindow.setContent("道路损害， 在里程桩8K+100处");
            map.infoWindow.show(point);
            map.centerAt(point);
        })
}

/**
 * 指定单个图层显示隐藏
 * @param layers
 * @param type
 * @param flag
 */
function singleLayerShow(layers, type, flag) {
    if (layers[type]) {
        if (flag) {
            layers[type].show();
        } else {
            layers[type].hide();
        }
    }
}

/**
 * 拉框查询
 * @param map
 * @param layer
 * @param uuid
 * @param symbol
 */
function selectFeature(map, layer, uuid, symbol) {

    require(
        [
            "custom/util",
            "dojo/domReady!"
        ], function (Util) {
            map.graphics.clear();
            map.infoWindow.hide();
            Util.selectFeature(map, layer, uuid, symbol)
        })
}

/**
 * 清空map.graphics 和 featurelayer层的选中状态
 * @param mlayers
 * @param arr
 */
function clearSelection(layers, arr) {
    map.graphics.clear();
    map.infoWindow.hide();
    if (arr && arr.length > 0) {
        arr.forEach(function (key) {
            layers[key].clearSelection();
        });
    } else {
        Object.keys(layers).forEach(function (key) {
            layers[key].clearSelection();
        });
    }
}

/**
 *
 * 定位一辆公交车
 * @param map
 * @param busNo
 * @param lon
 * @param lat
 */
function locbus(map, busNo, lon, lat, speed) {
    var url = gisstaticresourcebaseurl + "/images/locbus.png";
    require([
        "esri/geometry/Point",
        "esri/graphic",
        "esri/symbols/PictureMarkerSymbol",
        "esri/geometry/webMercatorUtils",
        "esri/symbols/TextSymbol",
        "esri/Color",
        "esri/symbols/Font",
        "dojo/domReady!"
    ], function (Point, Graphic, PictureMarkerSymbol,
                 webMercatorUtils, TextSymbol, Color, Font) {
        clear();
        var p = new Point(Number(lon), Number(lat));
        var geo = webMercatorUtils.geographicToWebMercator(p);
        var geom = webMercatorUtils.geographicToWebMercator(p);
        var symbol = new PictureMarkerSymbol(url, 24, 24);
        symbol.setAngle(0);
        var graphic = new Graphic(geo, symbol);
        map.graphics.add(graphic);
        map.infoWindow.setTitle("车牌" + busNo);
        map.infoWindow.setContent("当前速度是:" + Number(speed) + "Km/h");
        map.infoWindow.show(geo);
        var textSymbol = new TextSymbol(busNo).setColor(
            new Color([255, 0, 0])).setAlign(Font.ALIGN_MIDDLE).setAngle(0).setFont(
            new Font("16pt").setWeight(Font.WEIGHT_NORMAL));
        var grap = new Graphic(geom, textSymbol);
        grap.setSymbol(textSymbol);
        map.graphics.add(grap);
        map.centerAt(geo);
    })
}

/**
 * 定位一辆巡查车
 * @param map
 * @param busNo
 * @param lon
 * @param lat
 */
function locxuncha(map, busNo, lon, lat, busType) {
    var url;
    require([
        "esri/geometry/Point",
        "esri/graphic",
        "esri/symbols/PictureMarkerSymbol",
        "esri/geometry/webMercatorUtils",
        "esri/symbols/TextSymbol",
        "esri/Color",
        "esri/symbols/Font",
        "dojo/domReady!"
    ], function (Point, Graphic, PictureMarkerSymbol,
                 webMercatorUtils, TextSymbol, Color, Font) {
        clear();
        var p = new Point(Number(lon), Number(lat));
        var geo = webMercatorUtils.geographicToWebMercator(p);
        var geom = webMercatorUtils.geographicToWebMercator(p);
        //1:路政巡查车   2：养护巡查车  3：养护公司巡查车
        if (busType == 1) {
            url = gisstaticresourcebaseurl + "/images/lzxuncha.png";
        } else if (busType == 2) {
            url = gisstaticresourcebaseurl + "/images/yhxuncha.png";
        } else if (busType == 3) {
            url = gisstaticresourcebaseurl + "/images/yhgsxuncha.png";
        }
        var symbol = new PictureMarkerSymbol(url, 24, 24);
        symbol.setAngle(0);
        var graphic = new Graphic(geo, symbol);
        map.graphics.add(graphic);
        var textSymbol = new TextSymbol(busNo).setColor(
            new Color([255, 0, 0])).setAlign(Font.ALIGN_MIDDLE).setAngle(0).setFont(
            new Font("16pt").setWeight(Font.WEIGHT_NORMAL));
        var grap = new Graphic(geom, textSymbol);
        grap.setSymbol(textSymbol);
        map.graphics.add(grap);
        map.centerAt(geo);
    })
}

/**
 * 定位多辆公交车
 * @param map
 * @param busNo
 * @param lon
 * @param lat
 */
function locbuses(map, points) {
    //定位多辆公交车用下面图片地址
    var url = gisstaticresourcebaseurl + "/images/locbus.png";
    require([
        "esri/geometry/Point",
        "esri/graphic",
        "esri/layers/GraphicsLayer",
        "esri/symbols/PictureMarkerSymbol",
        "esri/geometry/webMercatorUtils",
        "esri/symbols/TextSymbol",
        "esri/Color",
        "esri/symbols/Font",
        "esri/SpatialReference",
        "dojo/domReady!"
    ], function (Point, Graphic, GraphicsLayer, PictureMarkerSymbol,
                 webMercatorUtils, TextSymbol, Color, Font, SpatialReference) {
        clear();
        for (var i = 0; i < points.length; i++) {
            var point = points[i];
            var p = new Point(Number(point.Lng), Number(point.Lat), new SpatialReference({wkid: 4326}));
            var geo = webMercatorUtils.geographicToWebMercator(p);
            var geom = webMercatorUtils.geographicToWebMercator(p);
            var symbol = new PictureMarkerSymbol(url, 24, 24);
            symbol.setAngle(0);
            var graphic = new Graphic(geo, symbol);
            map.graphics.add(graphic);
            var textSymbol = new TextSymbol(point.carNo).setColor(
                new Color([255, 0, 0])).setAlign(Font.ALIGN_MIDDLE).setAngle(0).setFont(
                new Font("16pt").setWeight(Font.WEIGHT_NORMAL));
            var grap = new Graphic(geom, textSymbol);
            grap.setSymbol(textSymbol);
            map.graphics.add(grap);
        }
        var pss = new Point(120.429, 37.355);
        map.centerAndZoom(pss, 13);
    })
}

/**
 * 定位多辆巡查车
 * @param map
 * @param points
 */
function loclotsxuncha(map, points) {
    var url;
    require([
        "esri/geometry/Point",
        "esri/graphic",
        "esri/layers/GraphicsLayer",
        "esri/symbols/PictureMarkerSymbol",
        "esri/geometry/webMercatorUtils",
        "esri/symbols/TextSymbol",
        "esri/Color",
        "esri/symbols/Font",
        "esri/SpatialReference",
        "dojo/domReady!"
    ], function (Point, Graphic, GraphicsLayer, PictureMarkerSymbol,
                 webMercatorUtils, TextSymbol, Color, Font, SpatialReference) {
        clear();
        for (var i = 0; i < points.length; i++) {
            var point = points[i];
            var p = new Point(Number(point.Lng), Number(point.Lat), new SpatialReference({wkid: 4326}));
            var geo = webMercatorUtils.geographicToWebMercator(p);
            var geom = webMercatorUtils.geographicToWebMercator(p);
            if (point.busType == 1) {
                url = gisstaticresourcebaseurl + "/images/lzxuncha.png";
            } else if (point.busType == 2) {
                url = gisstaticresourcebaseurl + "/images/yhxuncha.png";
            } else if (point.busType == 3) {
                url = gisstaticresourcebaseurl + "/images/yhgsxuncha.png";
            }
            var symbol = new PictureMarkerSymbol(url, 48, 48);
            symbol.setAngle(0);
            var graphic = new Graphic(geo, symbol);
            map.graphics.add(graphic);
            var textSymbol;
            if (point.Speed == 0.0) {
                textSymbol = new TextSymbol(point.carNo).setColor(
                    new Color([255, 0, 0])).setAlign(Font.ALIGN_MIDDLE).setAngle(0).setOffset(1, 7).setFont(
                    new Font("12pt").setWeight(Font.WEIGHT_NORMAL));
            } else {
                textSymbol = new TextSymbol(point.carNo).setColor(
                    new Color([0, 0, 255])).setAlign(Font.ALIGN_MIDDLE).setAngle(0).setOffset(1, 7).setFont(
                    new Font("12pt").setWeight(Font.WEIGHT_NORMAL));
            }
            var grap = new Graphic(geom, textSymbol);
            grap.setSymbol(textSymbol);
            map.graphics.add(grap);
        }
        var pss = new Point(120.429, 37.355);
        map.centerAt(pss);
    })
}

/**
 * gps转平面坐标
 * @param id
 * @param lon
 * @param lat
 */
function transCoord(id, lon, lat) {
    require(
        ["esri/geometry/Point",
            "esri/geometry/webMercatorUtils"], function (Point, webMercatorUtils) {
            var p = new Point(lon, lat);
            var geo = webMercatorUtils.geographicToWebMercator(p);
        })
}

/**
 * 清除层
 * @param map
 */
function clean(map) {
    map.graphics.clear();
}

/**
 * 前视图
 * @param map
 */
function preview(map) {
    require(["esri/toolbars/navigation"], function (Navigation) {
        var navToolbar = new Navigation(map);
        navToolbar.zoomToPrevExtent();
    });
}

/**
 * 后视图
 * @param map
 */
function nextview(map) {
    require(["esri/toolbars/navigation"], function (Navigation) {
        var navToolbar = new Navigation(map);
        navToolbar.zoomToNextExtent();
    });
}

/**
 * 拉框放大
 * @param map
 */
function bigpull(map) {
    require(["esri/toolbars/navigation"], function (Navigation) {
        navToolbar.activate(Navigation.ZOOM_IN);
    })
}

/**
 * 拉框缩小
 * @param map
 */
function smallpull(map) {
    require(["esri/toolbars/navigation"], function (Navigation) {

        navToolbar.activate(Navigation.ZOOM_OUT);
    })
}

/**
 * 平移
 * @param map
 */
function moving(map) {
    require(["esri/toolbars/navigation"], function (Navigation) {
        var navToolbar = new Navigation(map);
        navToolbar.activate(Navigation.PAN);
    })
}

/**
 * 加载影像地图
 * @param map
 * @param basemaps
 */
function loadImg(map, basemaps) {
    loadBaseMapResource(function (arr) {
        basemaps = arr;
    });
    loadImgMap(map, basemaps);
}

/**
 * 加载矢量地图
 * @param map
 * @param basemaps
 */
function loadVec(map, basemaps) {
    loadBaseMapResource(function (arr) {
        basemaps = arr;
    });
    loadVecMap(map, basemaps);
}

/**
 * 显示多个事件
 */
function locEvents(map, points) {

    require([
        "esri/geometry/Point",
        "esri/graphic",
        "esri/layers/GraphicsLayer",
        "esri/symbols/PictureMarkerSymbol",
         "esri/geometry/webMercatorUtils",
        "esri/symbols/TextSymbol",
        "esri/Color",
        "esri/symbols/Font",
        "esri/SpatialReference",
        // "esri/InfoTemplate",
        "dojo/domReady!"
    ], function (Point, Graphic, GraphicsLayer, PictureMarkerSymbol,webMercatorUtils,
                  TextSymbol, Color, Font, SpatialReference) {
        clear();
        var p;
        var eventLayer = new GraphicsLayer({id: "eventLayer"});
        for (var i = 0; i < points.length; i++) {
            var point = points[i];
            var url = "";
            switch (point.degree) {
                case '轻微':
                    url = gisstaticresourcebaseurl + "/images/llan.png";
                    break;
                case '轻':
                    url = gisstaticresourcebaseurl + "/images/llv.png";
                    break;
                case '中':
                    url = gisstaticresourcebaseurl + "/images/lhuang.png";
                    break;
                case '严重':
                    url = gisstaticresourcebaseurl + "/images/lcheng.png";
                    break;
                case '特别严重':
                    url = gisstaticresourcebaseurl + "/images/lhong.png";
                    break;
                default:
                    url = null;
            }
            p = new Point(Number(point.Lng), Number(point.Lat), new SpatialReference({wkid: 3857}));
              var ps = webMercatorUtils.geographicToWebMercator(p);
              console.log(ps)

            var symbol = new PictureMarkerSymbol(url, 24, 24);
            var graphic = new Graphic(p, symbol);
             graphic.setAttributes({"desc": point.info, 'id': point.id});
            graphic.setAttributes({'id': point.id});
            eventLayer.add(graphic);
        }
        eventLayer.on('click', function (event) {
            var config = {
                url: '/lzgl/gisComprehensiveDisplayController/showEventAlert/' + event.graphic.attributes.id,
                title: "事件详情",
                callback: function () {

                },
                width: '600px',
                height: '500px'
            };
            JGP.$dialog(config);
        });
        map.addLayer(eventLayer);
        map.centerAndZoom(p, 10);
    })
}

/**
 * 点击地图上任意点，获取当前点坐标
 */
function pointXY(toolbar,callback) {
    require([
        "esri/map",
        "esri/geometry/Point",
        "esri/layers/GraphicsLayer",
        "esri/graphic",
        "esri/geometry/webMercatorUtils",
        "esri/symbols/SimpleMarkerSymbol",
        "esri/symbols/SimpleLineSymbol",
        "esri/SpatialReference",
        "esri/toolbars/draw",
        "dojo/domReady!"
    ],function (Map,Point,GraphicsLayer,Graphic,webMercatorUtils,
                SimpleMarkerSymbol,SimpleLineSymbol,SpatialReference,Draw) {

        // map.on('click',function (p) {
        //     var lat = Math.round(p.mapPoint.getLatitude() * 1000) / 1000;
        //     var lon = Math.round(p.mapPoint.getLongitude() * 1000) / 1000;
        //     var point = new Point(Number(lon),Number(lat),new SpatialReference({wkid: 4326}));
        //     var webPoint =webMercatorUtils.geographicToWebMercator(point);
        //     var symbol = new PictureMarkerSymbol(pictureURL+"xunchaone.png",24,24);
        //     var graphic = new Graphic(webPoint,symbol);
        //     map.graphics.add(graphic);
        //     console.log(graphic);
        //
        // });
        toolbar.activate(Draw.POINT);
        toolbar.on("draw-end", function (evt) {
            toolbar.deactivate();
            var point = evt.geometry;
            var symbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_SQUARE,5,
                new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,1,"red"),"green");
            var graphic = new Graphic(point,symbol);
            map.graphics.add(graphic);
            callback(point.x, point.y);
    });

    })
}

/**
 * 显示多个地理要素
 */

function centerLocate(map, points,callback) {
    //var url = gisstaticresourcebaseurl +"/images/locevent.png";
    // var url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1547284609840&di=c78d6b4ab23e2c2842a9678032a5d3cb&imgtype=0&src=http%3A%2F%2Fpic39.photophoto.cn%2F20160607%2F0018090919909250_b.jpg";
    require([
        "esri/geometry/Point",
        "esri/graphic",
        "esri/layers/GraphicsLayer",
        "esri/symbols/PictureMarkerSymbol",
        "esri/geometry/webMercatorUtils",
        "esri/symbols/TextSymbol",
        "esri/Color",
        "esri/symbols/Font",
        "esri/SpatialReference",
        "dojo/domReady!"
    ], function (Point, Graphic, GraphicsLayer, PictureMarkerSymbol,
                 webMercatorUtils, TextSymbol, Color, Font, SpatialReference) {
        clear();
        var p;
        var eventLayers = new GraphicsLayer({id: "eventLayers"});
        for (var i = 0; i < points.length; i++) {
            var point = points[i];
            var url = pictureURL + point.url;
            p = new Point(Number(point.x), Number(point.y), new SpatialReference({wkid: 4326}));
            var ps = webMercatorUtils.geographicToWebMercator(p);
            var symbol = new PictureMarkerSymbol(url, 24, 24);
            var graphic = new Graphic(ps, symbol);
            graphic.setAttributes({'id': point.id});
            eventLayers.add(graphic);
        }
        map.addLayer(eventLayers);
        map.centerAndZoom(ps, 10);

        eventLayers.on('click',function (evt) {
            var eventId = evt.graphic.attributes.id;
            callback(eventId);
        });
    })
}


/**
 * 显示单个事件
 */
function lonelyEvents(point) {
    var url = gisstaticresourcebaseurl + "/images/dog.jpg";
    require([
        "esri/geometry/Point",
        "esri/graphic",
        "esri/layers/GraphicsLayer",
        "esri/symbols/PictureMarkerSymbol",
        "esri/InfoTemplate",
        "esri/SpatialReference"
    ], function (Point, Graphic, GraphicsLayer, PictureMarkerSymbol, InfoTemplate, SpatialReference) {
        var layer = map.getLayer("eventLayer");
        if (!layer) {
            layer = new GraphicsLayer({id: "eventLayer"});
        }
        layer.clear();
        var p = new Point(Number(point.Lng), Number(point.Lat), new SpatialReference({wkid: 3857}));
        var symbol = new PictureMarkerSymbol(url, 24, 24);
        var graphic = new Graphic(p, symbol);
        graphic.setAttributes({"desc": point.info});
        graphic.setInfoTemplate(new InfoTemplate("事件", "${desc}"));
        layer.add(graphic);
        map.addLayer(layer);
        map.centerAt(p);
    })
}

/**
 * 显示多个控制点
 */
function showctlps(map, points, callback) {
    require([
        "esri/geometry/Point",
        "esri/graphic",
        "esri/layers/GraphicsLayer",
        "esri/symbols/PictureMarkerSymbol",
        "esri/geometry/webMercatorUtils",
        "esri/symbols/TextSymbol",
        "esri/Color",
        "esri/symbols/Font",
        "esri/SpatialReference",
        "dojo/domReady!"
    ], function (Point, Graphic, GraphicsLayer, PictureMarkerSymbol,
                 webMercatorUtils, TextSymbol, Color, Font, SpatialReference) {
        var p;
        var graphicLayer = new GraphicsLayer({id: "ctlpLayer"});
        for (var i = 0; i < points.length; i++) {
            var point = points[i];
            p = new Point(Number(point.Lng), Number(point.Lat), new SpatialReference({wkid: 3857}));
            var url;
            if (point.passTime) {
                url = gisstaticresourcebaseurl + "/images/ccctlps.png";  //有车经过，图片为蓝色
            } else {
                url = gisstaticresourcebaseurl + "/images/ccctlp.png";  //没车经过，图片为红色
            }
            var symbol = new PictureMarkerSymbol(url, 16, 16);
            var graphic = new Graphic(p, symbol);
            graphic.setAttributes({
                "desc": point.info,
                "passTime": point.passTime,
                "id": point.id,
                startTime: point.startTime,
                endTime: point.endTime
            });
            graphicLayer.add(graphic);
        }
        map.addLayer(graphicLayer);
        graphicLayer.on("click", function (evt) {
            callback(evt)
        })
        map.centerAndZoom(p, 10);
    })
}

/**
 * 显示单个控制点
 */
function lonelyCtlp(map, Lng, Lat, desc) {
    var url = gisstaticresourcebaseurl + "/images/ccctlp.png";
    require([
        "esri/geometry/Point",
        "esri/graphic",
        "esri/layers/GraphicsLayer",
        "esri/symbols/PictureMarkerSymbol",
        "esri/SpatialReference",
        "dojo/domReady!"
    ], function (Point, Graphic, GraphicsLayer, PictureMarkerSymbol, SpatialReference) {
        var layer = map.getLayer('ctlpLayer');
        if (!layer) {
            layer = new GraphicsLayer({id: "ctlpLayer"});
            map.addLayer(layer);
        }
        layer.clear();
        var p = new Point(Number(Lng), Number(Lat), new SpatialReference({wkid: 3857}));
        var symbol = new PictureMarkerSymbol(url, 24, 24);
        var graphic = new Graphic(p, symbol);
        graphic.setAttributes({"desc": p.desc, "id": p.id});
        layer.add(graphic);
        map.centerAt(p);
    })
}

/**
 * 清空
 */
function clear() {
    map.graphics.clear();
    map.infoWindow.hide();


    var dlLayer = map.getLayer("eventLayers");
    if(dlLayer){
        map.removeLayer(dlLayer);
    }

    var layer = map.getLayer("eventLayer");
    if (layer) {
        map.removeLayer(layer);
    }

    var ctlLayer = map.getLayer("ctlpLayer");
    if (ctlLayer) {
        map.removeLayer(ctlLayer);
    }

    var carLayer = map.getLayer("carLayer");
    if (carLayer) {
        map.removeLayer(carLayer);
        carLayer = null;
    }
    var lineLayer = map.getLayer("lineLayer");
    if (lineLayer) {
        map.removeLayer(lineLayer);
        lineLayer = null;
    }


}

//加载影像跟加载矢量的方法，页面暂不调用，后期需要修改！！！！！！！！！！


/**
 * 定位路面
 */
function locRoads(LDXLH, LXBM) {
    require(
        [
            "esri/layers/FeatureLayer",
            "esri/tasks/query",
            "esri/geometry/Point",
            "esri/symbols/SimpleFillSymbol",
            "esri/symbols/SimpleLineSymbol",
            "esri/Color",
            "esri/graphic"
        ], function (FeatureLayer, Query, Point, SimpleFillSymbol, SimpleLineSymbol, Color, Graphic) {
            var featureLayer = new FeatureLayer(gisUrl + "/arcgis/rest/services/zyloads/MapServer/1", {
                mode: FeatureLayer.MODE_ONDEMAND,
                outFields: ["*"],
                // infoTemplate:new InfoTemplate("${LXMC}-${LDXLH}-${UPORDOWN}")
            });
            var query = new Query();
            query.where = "LDXLH = '" + LDXLH + "'" + "and" + " " + "LXBM ='" + LXBM + "'";
            featureLayer.queryFeatures(query, function (response) {
                var feature;
                var features = response.features;
                for (var i = 0; i < features.length; i++) {
                    feature = features[i];
                    var geometry = feature.geometry;
                    var attributes = feature.attributes;
                    var pt = new Point(geometry.rings[0][0][0], geometry.rings[0][0][1], featureLayer.spatialReference);
                    map.centerAndZoom(pt, 13);
                    var symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
                        new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT,
                            new Color([255, 0, 0]), 2), new Color([255, 255, 0, 0.25])
                    );
                    var graphic = new Graphic(geometry, symbol, attributes);
                    map.graphics.add(graphic);
                }
                var clickListener = map.graphics.on("click", function (evt) {
                    var lineCode = evt.graphic.attributes.LXBM;
                    var xh = evt.graphic.attributes.LDXLH;
                    linkClick(lineCode, xh);
                });
            })
        })
}


/**
 * 道路路段点击事件方法体具体实现
 * @param obj
 */
function linkClick(lineCode, xh) {
    debugger;
    var config = {
        url: '/lcda/lclinkController/editMaplcLink/' + lineCode + '/' + xh,
        title: "道路路段详情",
        callback: function () {

        },
        width: '900px',
        height: '550px'
    }
    JGP.$dialog(config)
}
